import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {API, AppConstants, Components, MsgConstants, SSOConstants} from '../constants/constants';
import {DataStorageUtil} from '../util/data-storage-util';
import {AppConfig} from '../app.config';
import {TokenUtil} from '../util/token-util';
import {RequestUtil} from '../util/request-util';
import {MsgResult} from '../models/msg-result';
import {Observable} from 'rxjs/Observable';
import {MenusService} from '../services/menus.service';

@Injectable()
export class ClientAuthResolveService implements Resolve<string>{

  constructor(
    private dataStorage:DataStorageUtil,
    private request : RequestUtil,
    private menus : MenusService,
    private tokenUtil : TokenUtil
  ) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):  Promise<string> | string {
    //是否开启统一登录
    if (!!AppConfig.SSO) {
      let params = route.paramMap;
      if(!params || params.keys.length == 0){
        params = route.queryParamMap;
      }
      return this.clientAuth(params);
    }else{
      return Components.authenComponent;
    }
  }


  private clientAuth(client:any):Promise<string> | string{
    let appId = client.get("appId");
    let appKey = client.get("appKey");
    let accountName = client.get("accountName");
    let scope = client.get("scope");
    let redirectUrl = client.get("redirectUrl");

    let params = "appId="+ appId + "&appKey="+ appKey + "&accountName="+accountName+"&scope="+scope;
    return (this.request.post(API.clientAuth,params) as Observable<MsgResult>).toPromise().then(
      result => this.processResult(result,redirectUrl),
      error =>  this.errorResult(error)
    );
  }

  /**
   * process result
   * @param result
   */
  private processResult = (result: MsgResult,redirectUrl:string): Promise<string> | string => {
    if (!!result && result.code == MsgConstants.MSG_CODE_OK) {
      let theme = result.data.theme || 'default';
      let uri = result.data.uri || '';
      let portal = result.data.portal || 'default';

      this.dataStorage.set(AppConstants.isLogin,AppConstants.loginSucess);
      this.dataStorage.set(AppConstants.theme,theme);
      this.dataStorage.set(AppConstants.portal,portal);
      this.dataStorage.set(AppConstants.uri,uri);

      this.tokenUtil.setToken(result.data.token,result.data.refreshToken,result.data.expire);

      let home = AppConstants.homePrefix;

      //如果指定跳转页面，检查是否拥有此菜单权限，有则组合id后返回，否则返回null
      if(redirectUrl){
        return this.menus.checkPermission(redirectUrl).then(
          specialUrl => {
            if(!!specialUrl){
              home += specialUrl.startsWith("/") ? portal + specialUrl : portal + "/" + specialUrl;
              this.dataStorage.set(AppConstants.home, home);
              return home;
            }else{
              let noPermi = "无权访问";
              return this.errorResult(noPermi);
            }
          }
        );
      }else{
        if (!!uri) {
          home += uri.startsWith("/") ? portal + uri : portal + "/" + uri;
        } else {
          home += portal;
        }

        this.dataStorage.set(AppConstants.home, home);
        return home;
      }
    } else {
      return this.errorResult(result.message);
    }
  };

  errorResult = (error:string):Promise<string> | string => {
    this.dataStorage.set(SSOConstants.error,error);
    return Components.errorComponent;
  }
}
